package com.elong.android.specialhouse.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.InputFilter;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.elong.android.specialhouse.ApartmentAPI;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.JSONConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.account.Account;
import com.elong.android.specialhouse.base.BaseVolleyActivity;
import com.elong.android.specialhouse.base.DialogUtils;
import com.elong.android.specialhouse.entity.response.LoginRegisterResp;
import com.elong.android.specialhouse.request.GetVerifyCodeReq;
import com.elong.android.specialhouse.request.LoginReq;
import com.elong.android.specialhouse.utils.AESUtils;
import com.elong.android.specialhouse.utils.ElongValidator;
import com.elong.android.specialhouse.utils.InputFilterUtils;
import com.elong.android.specialhouse.utils.StringUtils;
import com.elong.android.specialhouse.utils.ToastUtils;
import com.elong.android.specialhouse.utils.Utils;
import com.elong.framework.netmid.ElongRequest;
import com.elong.framework.netmid.response.IResponse;
import com.elong.framework.netmid.response.StringResponse;

public class LoginActivity extends BaseVolleyActivity<IResponse<?>> {
    public static final String TAG = "com.elong.android.youfang.activity.LoginActivity";
    /**
     * 跳到注册页请求码
     */
    private static final int REQUEST_CODE_REGISTER = 0;
    /**
     * 跳到个人中心页的请求码
     */
    private static final int REQUEST_CODE_ACCOUNTINFO = 1;
    /**
     * 昵称不能为空的错误码
     */
    private static final String ERROR_CODE_NICKNAME_NULL = "2482";
    /**
     * 验证码下发类型，【1:注册；2:登录】 这里是登录
     */
    public static final int VERIFY_CODE_TYPE_LOGIN = 2;
    /**
     * 登录模式：10：手机号+密码
     */
    public final static String LOGIN_MODE_PWD = "10";
    /**
     * 登录模式：20：手机号+验证码
     */
    public final static String LOGIN_MODE_VERIFY_CODE = "20";
    /**
     * 按钮：点击时，切换到普通登录
     */
    private TextView tvCommenLogin;
    /**
     * 按钮：点击时，切换到手机动态登录
     */
    private TextView tvDynamicLogin;
    /**
     * 账号，也是手机号
     */
    private EditText etPhoneNumber;
    /**
     * 普通登录模式下是密码框，动态登录下是验证码框。
     */
    private EditText etPassword;
    private EditText etVerifyCode;
    private View viewUnderlineLeft;
    private View viewUnderlineRight;
    private TextView tvGetVerifyCode;
    /**
     * 普通登录模式下是“账号”，动态登录下是“手机号”。
     */
    private TextView tvAccountNameLabel;
    /**
     * 普通登录模式下是“密码”，动态登录下是“验证码”。
     */
    private TextView tvPasswordLabel;
    private TextView tvLogin;
    private TextView tvFastRegister;
    private boolean isCommonLogin = true;
    /**
     * 手机号
     */
    private String mPhoneNumber;
    /**
     * 登录的密码或者验证码
     */
    private String mValidateValue;

    /**
     * 读秒计时器，用来做验证码倒计时
     */
    private TimeCount mTimeCount;
    /**
     * 动态登录,获取验证码时，临时保存手机号
     */
    private String mTempPhoneNumber;

    private String mComeFrom;
    private long exitTime;

    @Override
    protected void initContentView() {
        setContentView(R.layout.act_login);
        setHeader(R.string.login);
        tvCommenLogin = (TextView) findViewById(R.id.tv_commen_login);
        tvDynamicLogin = (TextView) findViewById(R.id.tv_dynamic_login);
        etPhoneNumber = (EditText) findViewById(R.id.et_username);
        etPassword = (EditText) findViewById(R.id.et_password);
        etVerifyCode = (EditText) findViewById(R.id.et_verify_code);
        viewUnderlineLeft = findViewById(R.id.view_underline_left);
        viewUnderlineRight = findViewById(R.id.view_underline_right);
        tvGetVerifyCode = (TextView) findViewById(R.id.tv_get_verify_code);
        tvAccountNameLabel = (TextView) findViewById(R.id.tv_username_label);
        tvPasswordLabel = (TextView) findViewById(R.id.tv_password_label);
        tvLogin = (TextView) findViewById(R.id.tv_login);
        tvFastRegister = (TextView) findViewById(R.id.tv_fast_regist);
        tvFastRegister.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
        tvFastRegister.getPaint().setAntiAlias(true);
        refreshLoginType();
        tvCommenLogin.setOnClickListener(this);
        tvDynamicLogin.setOnClickListener(this);
        tvGetVerifyCode.setOnClickListener(this);
        tvLogin.setOnClickListener(this);
        tvFastRegister.setOnClickListener(this);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initData();
    }

    private void initData() {
        mComeFrom = getIntent().getStringExtra(AppConstants.BUNDLE_KEY_COME_FROM);
        if (StringUtils.isEmpty(mComeFrom)) {
            mComeFrom = getIntent().getStringExtra(AppConstants.ACTIVITY_KEY_FROM_WHERE);
        }

        // 控制密码只能输入数字或者英文，且长度为6-15
        etPassword.setFilters(new InputFilter[]{InputFilterUtils.getNumAndEnInputFilter(),
                new InputFilter.LengthFilter(AppConstants.MAX_PASSWORD_LENGHT)});
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isCommonLogin) {
            initLoadInfo();
        }
    }

    private void initLoadInfo() {
        String aesPhoneNumber = Account.getInstance().getPhoneNumber();
        if (StringUtils.isEmpty(aesPhoneNumber)) {
            return;
        }
        String phoneNumber;
        phoneNumber = AESUtils.decodingAndDecrypt(aesPhoneNumber);
        if (StringUtils.isNotEmpty(phoneNumber)) {
            etPhoneNumber.setText(phoneNumber);
            etPhoneNumber.setSelection(phoneNumber.length());
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_commen_login:
                isCommonLogin = true;
                refreshLoginType();
                initLoadInfo();
                break;
            case R.id.tv_dynamic_login:
                isCommonLogin = false;
                refreshLoginType();
                break;
            case R.id.tv_get_verify_code:
                onClickGetVerifyCodeBtn();
                break;
            case R.id.tv_login:
                validate();
                break;
            case R.id.tv_fast_regist:
                goToRegisterPage();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_REGISTER:
                    back();

                    // 若是正常登陆，则跳到主页，否则返回原先页
//                    if (isNormalLogin()) {
//                        goToHome();
//                    } else {
//                        back();
//                    }
                    break;
                case REQUEST_CODE_ACCOUNTINFO:
                    goToHome();
                    break;
            }
        }
    }

    private void onClickGetVerifyCodeBtn() {
        mPhoneNumber = etPhoneNumber.getText().toString().trim();
        if (!ElongValidator.isInlandPhone(etPhoneNumber.getText().toString()
                .trim())) {
            ToastUtils.show(this, R.string.login_please_input_correct_phone,
                    Toast.LENGTH_LONG);
            return;
        }
        // 初始化计时器
        mTimeCount = new TimeCount(AppConstants.MILLIS_IN_FUTURE, AppConstants.COUNT_DOWN_INTERVAL);
        // 发送获取验证码请求
        requestVerifyCode();
    }

    /**
     * 请求验证码
     */
    private void requestVerifyCode() {
        GetVerifyCodeReq req = new GetVerifyCodeReq();
        req.Mobile = mPhoneNumber;
        req.CodeType = VERIFY_CODE_TYPE_LOGIN;
        requestHttp(req, ApartmentAPI.getDynamicVerifyCode, StringResponse.class, true);
    }

    private void validate() {
        mPhoneNumber = etPhoneNumber.getText().toString().trim();
        String loginMode;
        if (StringUtils.isEmpty(mPhoneNumber)) {
            ToastUtils.show(this, R.string.login_username_cannot_null);
            return;
        }

        if (!ElongValidator.isInlandPhone(mPhoneNumber)) {
            ToastUtils.show(this, R.string.login_please_input_correct_phone);
            return;
        }

        if (isCommonLogin) {
            // 普通登录:手机号+密码
            mValidateValue = etPassword.getText().toString().trim();
            loginMode = LOGIN_MODE_PWD;
            if (StringUtils.isEmpty(mValidateValue)) {
                ToastUtils.show(this, R.string.login_password_cannot_null);
                return;
            }
            if (!ElongValidator.isPassword(mValidateValue)) {
                ToastUtils.show(this, R.string.login_password_formatter_not_correct);
                return;
            }
        } else {
            // 动态验证码登录：手机号+验证码
            mValidateValue = etVerifyCode.getText().toString().trim();
            loginMode = LOGIN_MODE_VERIFY_CODE;
            if (StringUtils.isEmpty(mValidateValue)) {
                ToastUtils.show(this, R.string.login_verify_code_cannot_null);
                return;
            }
            if (!ElongValidator.isVerifyCode(mValidateValue)) {
                ToastUtils.show(this, R.string.login_verify_code_formatter_not_correct);
                return;
            }
        }
        // 验证成功，进行登录请求
        requestLoad(loginMode);
    }

    /**
     * 请求登录操作
     */
    private void requestLoad(String loginMode) {
        // 提交登录操作
        LoginReq req = new LoginReq();
        req.LoginMode = loginMode;
        req.PhoneNumber = mPhoneNumber;
        req.ValidateValue = mValidateValue;
        requestHttp(req, ApartmentAPI.login, StringResponse.class, true);
    }

    @Override
    public void onTaskPost(ElongRequest request, IResponse<?> t) {
        super.onTaskPost(request, t);
        ApartmentAPI action = (ApartmentAPI) request.getRequestOption()
                .getHusky();
        JSONObject result = null;
        try {
            result = JSON.parseObject(((StringResponse) t).getContent());
        } catch (Exception e) {
            ToastUtils.show(this, R.string.parse_error);
            return;
        }
        if (result == null) {
            return;
        }

        if (ERROR_CODE_NICKNAME_NULL.equals(result.getString(JSONConstants.ATTR_ERRORCODE))) {
            // 当发生 “昵称为空时“ 错误时
            onNickNameNull(result);
            return;
        }

        // 过滤错误信息
        if (handleIsError(request, result)) {
            return;
        }
        switch (action) {
            // 获取验证码请求
            case getDynamicVerifyCode:
                // 成功
                if (!result.getBoolean(JSONConstants.ATTR_ISERROR)) {
                    ToastUtils.show(this, R.string.verify_code_sent_success);
                    // 开始读秒计时
                    mTimeCount.start();
                }
                break;
            // 登录请求
            case login:
                // 登录成功
                // 保存用户信息
                LoginRegisterResp resp = JSONObject.parseObject(
                        result.toJSONString(), LoginRegisterResp.class);
                if (resp != null) {
                    saveAccountInfo(resp, true);
                }
                setResult(Activity.RESULT_OK);

                back();

                // 如果是正常登陆，则跳到主页，否则返回原先的页面
//                if (isNormalLogin()) {
//                    // 跳转到主页
//                    goToHome();
//                } else {
//                    back();
//                }
                break;

            default:
                break;
        }
    }

    private void onNickNameNull(JSONObject result) {
        saveAccountInfo(JSONObject.parseObject(result.toJSONString(), LoginRegisterResp.class), false);

        DialogUtils.showInfoWithCustomText(this, getString(R.string.nickname_can_not_be_null), "",
                R.string.go_to_fill_nickname, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        gotoAccountInfoPage();
                    }
                });
    }

    private void gotoAccountInfoPage() {
//        Intent intent = new Intent(this, PerfectAccountInfoActivity.class);
//        startActivityForResult(intent, REQUEST_CODE_ACCOUNTINFO);
    }

    /**
     * 判断是否是正常登陆，
     *
     * @return
     */
    private boolean isNormalLogin() {
        return StringUtils.isEmpty(mComeFrom);
    }

    /**
     * 跳转到主页
     */
    private void goToHome() {
        Intent intent = new Intent(this, HomeActivity.class);
        intent.putExtra(AppConstants.BUNDLE_KEY_COME_FROM, TAG);
        Utils.clearTopActivity();
        startActivity(intent);
        back();
    }

    /**
     * 跳到注册页
     */
    private void goToRegisterPage() {
//        Intent intent = new Intent(this, RegisterActivity.class);
//        startActivityForResult(intent, REQUEST_CODE_REGISTER);
    }

    /**
     * 保存账号信息
     */
    private void saveAccountInfo(LoginRegisterResp resp, boolean isLogin) {
        Account.getInstance().setLogin(isLogin);
        Account.getInstance().refreshSessionToken(resp.AccessToken);
        Account.getInstance().setUserId(resp.Uid);
        Account.getInstance().setAvatar(resp.Avatar);
        Account.getInstance().setIdentityPass(resp.IdentityPass);
        Account.getInstance().setIdentityPassDecription(resp.IdentityPassDecription);
        Account.getInstance().setNickName(resp.NickName);
        Account.getInstance().setIsCustomer(resp.IsCustomer == 1);
        Account.getInstance().setIsLandlord(resp.IsLandlord == 1);
        savePhoneAndPWD();
    }

    /**
     * 保存手机号和密码
     */
    private void savePhoneAndPWD() {
        String aesPhoneNumber;
        aesPhoneNumber = AESUtils.encryptAndEncoding(mPhoneNumber);
        Account.getInstance().setPhoneNumber(aesPhoneNumber);
        // 密码在内部进行了加密,只有在普通登录模式下才保存密码
        if (isCommonLogin) {
            Account.getInstance().setPassword(mValidateValue);
        }
    }

    /**
     * 刷新登录的方式：普通登录or动态密码登录
     */
    private void refreshLoginType() {
        if (isCommonLogin) {
            // 临时保存动态登录时填写的手机号
            mTempPhoneNumber = etPhoneNumber.getText().toString().trim();
            // 普通登录
            tvCommenLogin.setTextColor(getResources().getColor(R.color.orange));
            viewUnderlineLeft.setBackgroundResource(R.color.orange);
            tvDynamicLogin.setTextColor(getResources().getColor(R.color.white));
            viewUnderlineRight.setBackgroundResource(R.color.white);
            tvGetVerifyCode.setVisibility(View.GONE);
            tvAccountNameLabel.setText(R.string.login_username_common);
            etPhoneNumber.setHint(R.string.login_input_phone_number_common_hint);
            tvPasswordLabel.setText(R.string.login_password_common);
            // 切换密码框与验证码框
            etPassword.setVisibility(View.VISIBLE);
            etVerifyCode.setVisibility(View.GONE);
        } else {
            // 动态验证码登录
            // 恢复之前输入的手机号
            etPhoneNumber.setText(mTempPhoneNumber);
            etPhoneNumber.setSelection(mTempPhoneNumber.length());
            tvCommenLogin.setTextColor(getResources().getColor(R.color.white));
            viewUnderlineLeft.setBackgroundResource(R.color.white);
            tvDynamicLogin.setTextColor(getResources().getColor(R.color.orange));
            viewUnderlineRight.setBackgroundResource(R.color.orange);
            tvGetVerifyCode.setVisibility(View.VISIBLE);
            tvAccountNameLabel.setText(R.string.login_username_dynamic);
            etPhoneNumber.setHint(R.string.login_input_phone_number_dynamic_hint);
            tvPasswordLabel.setText(R.string.login_password_dynamic);
            // 切换密码框与验证码框
            etPassword.setVisibility(View.GONE);
            etVerifyCode.setVisibility(View.VISIBLE);
        }
    }

    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            tvGetVerifyCode.setEnabled(false);
            tvGetVerifyCode.setBackgroundResource(R.drawable.btn_bg_gray_light_rect);
            String countDownHint = millisUntilFinished / AppConstants.COUNT_DOWN_INTERVAL
                    + getResources().getString(R.string.verify_code_right_text);
            tvGetVerifyCode.setText(countDownHint);
            AppConstants.TIMES_REMAIN = millisUntilFinished;
        }

        @Override
        public void onFinish() {
            AppConstants.TIMES_REMAIN = 0;
            tvGetVerifyCode.setText(R.string.login_get_verify_code);
            tvGetVerifyCode.setBackgroundResource(R.drawable.btn_bg_orange_dark_rect);
            // 设置验证码按钮的点击状态
            tvGetVerifyCode.setEnabled(true);
            cancelTimeCount();
            // refreshVerifyCodeBtnStatus(etPhoneNumber.getText().toString().trim());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        cancelTimeCount();
    }

    private void cancelTimeCount() {
        if (mTimeCount != null) {
            mTimeCount.cancel();
            mTimeCount = null;
        }
    }
}
